package com.steshov.trainer.dao;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.steshov.trainer.activities.TaskActivity;
import com.steshov.trainer.model.Task;
import com.steshov.trainer.utils.App;
import com.steshov.trainer.utils.DB_Utils;

public class TaskDAO {
	SQLiteDatabase db;

	{
		db = DB_Utils.db;
		Log.d("a", "DB: " + db);
	}

	public void peristTask(Context context, Task task, Boolean showMessage) {
		Log.d("db", "persisting Task:   " + task.toString());
		try {
			db.execSQL("INSERT INTO " + DB_Utils.TASKS_TAB_NAME
					+ " VALUES (null,'" + task.getExercise() + "',"
					+ task.getAmount() + "," + task.getTime() + ","
					+ task.getGenerated() + ");");
			if (showMessage) {
				App.msg(context, "Task is created.");
			}
		} catch (Exception e) {
			App.msg(context, "An error occureed During adding a Task");
			Log.d("db", "" + e);
		}
	}

	public void removeTask(Activity context, int taskId) {
		try {
			DB_Utils.showtable(DB_Utils.TASKS_TAB_NAME);
			db.execSQL("DELETE FROM " + DB_Utils.TASKS_TAB_NAME + " Where id="
					+ taskId + ";");
		} catch (Exception e) {
			Log.e("a", e + "");
			App.msg(context, e.toString());
		}
	}

	public void updateTask(TaskActivity context, Task task) {
		Log.d("db", "updating Task:   " + task.toString());
		try {
			db.execSQL("UPDATE " + DB_Utils.TASKS_TAB_NAME + " SET exercise ='"
					+ task.getExercise() + "', number = " + task.getAmount()
					+ ", time=" + task.getTime() + " where id=" + task.getId());
//			App.msg(context, "Task is updated.");
		} catch (Exception e) {
			App.msg(context, "An error occureed During updating a Task");
			Log.d("db", "" + e);
		}

	}

	public ArrayList<Task> getTasks(Activity activity) {
		try {
			ArrayList<Task> data = DB_Utils
					.convertCursorToListOfArrays("Select * from "
							+ DB_Utils.TASKS_TAB_NAME);
			return data;
		} catch (Exception e) {
			Log.d("db", "!!!!!!" + e.toString());
			App.msg(activity, e.toString());
		}
		return new ArrayList<Task>();
	}

	public void removeExercise(TaskActivity context, Task task) {
		try {
			db.execSQL("DELETE FROM " + DB_Utils.EXERCISE_TAB_NAME
					+ " Where id=" + task.getId() + ";");
		} catch (Exception e) {
			App.msg(context, e.toString());
		}
	}

	public String[] getExercises(Activity context) {
		try {
			return DB_Utils.convertCursorToArray("Select name from "
					+ DB_Utils.EXERCISE_TAB_NAME);
		} catch (Exception e) {
			App.msg(context, e.toString());
		}
		return new String[0];
	}

	public void removeGenerated(Activity context) {
		try {
			db.execSQL("DELETE FROM " + DB_Utils.TASKS_TAB_NAME
					+ " Where generated=1;");
		} catch (Exception e) {
			Log.e("a", e + "");
			App.msg(context, e.toString());
		}
	}
}